$(function() {
	
	// for validate image size
	var _superUploadFile = qq.FileUploader.prototype._uploadFile;
	
	// add validate image size
	qq.FileUploader.prototype._uploadFile = function(file) {
		var fileuploader = this, 
			reader, url, img;
		
		var imageSizes = this._options.imageSizes;

		if (imageSizes.length && /image/i.test(file.type) && window.FileReader) {

			img = new Image();
			img.onload = function() {
				var size = this.width + 'x' + this.height;
				
				if ($.inArray(size, imageSizes) !== -1) {
					_superUploadFile.call(fileuploader, file);
				} else {
					fileuploader._options.showMessage('Image size is invalid. Only ' + imageSizes.join(', ') + (imageSizes.length > 1 ? ' are' : ' is') + ' allowed.');
				}
			};
			
			reader = new FileReader();
			reader.onload = function(e) {
				img.src = e.target.result;
			};
			reader.readAsDataURL(file);
		} else {
			_superUploadFile.call(this, file);
		}
	};
	
	// disable drag drop to upload
	qq.FileUploader.prototype._setupDragDrop = function() {
		this._find(this._element, 'drop').style.display = 'none';
	};
	
	$.widget('ace.fileuploader', {
		options: {
			request: '',
			data: {},
			extensions: ['jpg', 'png', 'bmp', 'gif'],
			sizeLimit: 2097152,
			
			// width x height: ['100x100', '200x100']
			imageSizes: [],
			preview: false,
			
			// width x height
			previewImageSize: '48x48'
		},
		
		_create: function() {
			var that = this,
				
				// remain the original class name 'fileuploader-container', the new class name has the 'ace' namespace
				$container = $('<div class="ace-fileuploader-container fileuploader-container" />').insertAfter(this.element),
				
				buttonWrapper, button;
			
			this.uploader = new qq.FileUploader({
				element: $container.get(0),
				action: this.options.request,
				params: this.options.data,
				allowedExtensions: this.options.extensions,
				imageSizes: this.options.imageSizes,
				multiple: false,
				sizeLimit: this.options.sizeLimit,
				onSubmit: function(id, filename) {
					that.element.siblings('label.error').hide();
					$('.qq-upload-list li', $container).remove();
				},
				
				onComplete: function(id, filename, res) {
					if (res.status) {
						that.element.val(res.result);
						$('.qq-upload-list li', $container).delay(800).fadeOut(function() {
							$(this).remove();
						});
						
						if (that.preview) {
							that.preview.fadeIn().find('img').attr('src', res.src ? res.src : res.result);
						}
						
						that._trigger('complete', null, res);
						
						// remain old callback
						that._trigger('done');
					} else {
						 //$.FlashMessage('error: '+ res.msg);
					}
				},
				
				showMessage: function(message) {
					var $error = that.element.siblings('label.error');
					
					if (!$error.length) {
						
						// follow the jquery-validate-plugin standard
						$error = $('<label class="error" for="' + that.element.attr('id') + '" />').insertAfter(that.element);
					}
					$error.show().text(message);
					
					if (that.preview) {
						that.preview.hide();
					}
				}
			});
			
			buttonWrapper = this.uploader._button._element,
			button = buttonWrapper.firstChild;
			
			this.element.parent().css('position', 'relative');
			$(buttonWrapper).css({
				position: 'absolute',
				left: this.element.position().left + this.element.outerWidth() + 1,
				top: 0
			});
			
			// set the button to bootstrap style
			if (button.nodeType === 3) {
				button.nodeValue = '上传';
			    $(button).wrap('<button type="button" class="btn" />');
			}
			
			this._refresh();
		},
		
		_setOption: function(key, value) {
			var keys = {
				'request': 'action',
				'data': 'params',
				'extensions': 'allowedExtensions',
				'imageSizes': 'imageSizes'
			};
			
			this.uploader._options[keys[key]] = value;
			this._super(key, value);
			
			this._refresh();
		},
		
		_refresh: function() {
			if (this.preview) {
				this.preview.remove();
				this.preview = null;
			}
				
			if (this.options.preview) {
				this._preview();
			}
		},
		
		_preview: function() {
			var sizes = this.options.previewImageSize.split('x'),
				preview = $('<div class="ace-fileuploader-preview"><img class="thumbnail" alt="" src="" /></div>')
					.css({
						width: parseInt(sizes[0], 10) + 10,
						height: parseInt(sizes[1], 10) + 10,
						'margin-top': 5
					})
					.appendTo(this.element.parent())
					.hide()
					.find('img')
					.css({
						display: 'block',
						width: sizes[0],
						height: sizes[1]
					})
					.end(),
				
				path = $.trim(this.element.val());
			
			if (/^http:\/\/.+/.test(path)) {
				preview.show().find('img').attr('src', path);
			}
			
			this.preview = preview;
		},
		
		reset: function() {
			this.element.val('');
			if (this.preview) {
				this.preview.hide().find('img').attr('src', '');
			}
		}
	});
});
